package org.example.admin.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.error.ShouldContainOnlyKeys;
import org.example.admin.dto.Kaptcha;
import org.example.admin.dto.LoginDto;
import org.example.admin.dto.RegisterDto;
import org.example.admin.dto.UserAuthInfoDto;
import org.example.admin.service.AdminKaptchaService;
import org.example.admin.service.AdminUserService;
import org.example.common.utils.DateTimeUtil;
import org.example.common.utils.ResponseUtil;
import org.example.security.service.AuthService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/auth")
@Api(tags = "用户登陆与注册")
@Slf4j
public class AdminAuthController {

    AuthService authService;
    AdminUserService adminUserService;
    Producer kaptchaProducer;
    RedisTemplate<String, Object> redisTemplate;
    AdminKaptchaService adminKaptchaService;

    public AdminAuthController(AuthService authService, AdminUserService adminUserService, Producer kaptchaProducer, RedisTemplate<String, Object> redisTemplate, AdminKaptchaService adminKaptchaService) {
        this.authService = authService;
        this.adminUserService = adminUserService;
        this.kaptchaProducer = kaptchaProducer;
        this.redisTemplate = redisTemplate;
        this.adminKaptchaService = adminKaptchaService;
    }

    @PostMapping("/login")
    @ApiOperation("管理员登陆")
    public Object adminLogin(@RequestBody LoginDto loginDto){

        adminKaptchaService.verifyKaptcha(loginDto.getCode(), loginDto.getKaptchaId());
        String token = authService.login(loginDto.getUsername(), loginDto.getPassword());


        return ResponseUtil.ok(token);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Object adminRegister(@RequestBody RegisterDto registerDto){

        // TODO
        return null;
    }

    @GetMapping("/getUserAuthInfo")
    @ApiOperation("获得用户信息")
    public Object getUserAuthInfo(){

        UserAuthInfoDto userAuthInfo = adminUserService.getUserAuthInfo();

        return ResponseUtil.ok(userAuthInfo);
    }

    @GetMapping("/getKaptcha")
    @ApiOperation("获得验证码")
    public Object getKaptcha(){

        String text = kaptchaProducer.createText();
        log.info("验证码 {}", text);
        BufferedImage image = kaptchaProducer.createImage(text);

        String numberDateTimeString = DateTimeUtil.getNumberDateTimeString();
        Long increment = redisTemplate.opsForValue().increment("uniqueIncrement:" + numberDateTimeString, 1);
        redisTemplate.expire("uniqueIncrement:" + numberDateTimeString, 5, TimeUnit.SECONDS);
        String KaptchaId = numberDateTimeString + String.format("%1$06d", increment);
        log.info("kaptcha id : {}", KaptchaId);
        redisTemplate.opsForValue().set("kaptchaKey:" + KaptchaId, text, 3, TimeUnit.MINUTES);

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return ResponseUtil.ok(new Kaptcha(KaptchaId,
                    "data:image/jpeg;base64," + base64.replaceAll("\r\n", "")));
        } catch (IOException e) {
            return ResponseUtil.fail();
        }
    }
}
